package com.zq.leave.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zq.leave.entity.Approver;
import com.zq.leave.entity.dto.Result;
import com.zq.leave.service.ApproverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baicun
 * @since 2020-06-20
 */
@RestController
@CrossOrigin
@RequestMapping("/approver")
public class ApproverController {

    @Autowired
    private ApproverService approverService;

    //approver注册
    @PostMapping("/regist")
    public Result regist(@RequestBody Approver approver){
        Approver searchApprover = approverService.getOne(new QueryWrapper<Approver>().eq("username",approver.getUsername()));
        if (searchApprover != null){
            return Result.fail("用户名已存在！");
        }
        //MD5加密存进数据库
        approver.setPassword(DigestUtils.md5DigestAsHex(approver.getPassword().getBytes()));
        approver.setCreated(LocalDateTime.now());
        approverService.save(approver);
        return Result.success(null);
    }

    //approver登录
    @PostMapping("/login")
    public Result login(@RequestBody Approver approver){
        //MD5加密验证
        approver.setPassword(DigestUtils.md5DigestAsHex(approver.getPassword().getBytes()));
        Approver searchApprover = approverService.getOne(new QueryWrapper<Approver>().eq("username",approver.getUsername()));
        if (searchApprover==null){
            return Result.fail("该用户不存在");
        }
        if (searchApprover.getPassword().equals(approver.getPassword())){
            return Result.success(searchApprover);
        }else {
            return Result.fail("密码不正确！");
        }
    }
    //请假时要调用
    //查询所有approver
    @GetMapping("/getAllApprover")
    public Result getAllApprover(){
        List<Approver> approvers = approverService.list();
        return Result.success(approvers);
    }

}
